{% extends 'base.html' %}

{% block title %}首页{% endblock %}

{% block headerjs %}
<style xmlns:margin-bottom="http://www.w3.org/1999/xhtml">
    body {
        background-color: #f0f8ff;
    }
    form {
        position: relative;
        width: 150px;
        margin: 0 auto;
    }
    .d1 {
        float: right;
        line-height: 80px;
    }
    .d1 input {
        width: 100px;
        height: 30px;
        border: 2px solid darkred;
        border-radius: 5px;
        outline: none;
        background: white;
        color: #1e242a;
    }
    .article-box {
        border: 1px solid #ccc;
        padding: 10px;
        margin-bottom: 30px;
        background-color: #f9f9f9;
        border-radius: 5px;
    }
    .article-content {
        margin-top: 10px;
    }
    .latest-articles {
        margin-top: 50px; /* 调整这个值来控制距离 */
    }
    .follow-button {
        display: inline-flex;
        align-items: center;
        padding: 5px 10px;
        border: 2px solid black;
        border-radius: 5px;
        text-decoration: none;
        color: white;
        background-color: black;
        transition: all 0.3s ease;
    }
    .follow-button.active {
        color: black;
        background-color: white;
        border-color: black;
    }
    .follow-button .icon {
        margin-right: 5px;
        font-size: 16px;
        transition: all 0.3s ease;
    }
    .follow-button.text{
     transition: all 0.3s ease;
     }

</style>
{% endblock %}

{% block left %}
<div id="main">
    <div class="container">
        <section class="latest-articles">
            <h2 style="text-align:center; font-size:20px; margin-bottom:40px;">最新文章</h2>
            {% if articles %}
                {% for article in articles %}
                <article class="article-box">
                    <h3 style="text-align:center; font-weight: bold;">{{ article.title }}</h3>
                    <p class="meta">
                        作者：{{ article.author }}
                        <a href="#" class="follow-button" data-author-id="{{ article.author.id }}">
                            <span class="icon">+</span>
                            <span class="text">关注</span>
                        </a>
                    </p>
                    <p>
                        创建时间：{{ article.create_time }} · 修改时间：{{ article.update_time }} · {{article.comment_count}} 评论 · {{ article.views }} 阅读
                    </p>
                    <p>{{ article.content | truncatewords:1}}</p>
                    <div class="entry-meta">
                        <span class="article.category"><a href="#">{{ article.category.name }}</a></span>
                    </div>
                    <a href="{% url 'article_detail' article_id=article.id %}" style="display: block; text-align: center;">继续阅读</a>
                </article>
                {% endfor %}
            {% else %}
                <p>暂无文章。</p>
            {% endif %}
        </section>
    </div>

    <nav id="page-nav">
    {% if has_previous %}
       <a class="extend prev" rel="prev" href="{% url 'index_page' previous_page_number %}">« Prev</a>
    {% endif %}
    {% for page in page_list %}
        {% if current_page == page %}
          <a class="page-number current" href="{% url 'index_page' page %}">{{ page }}</a>
        {% else %}
        <a class="page-number" href="{% url 'index_page' page %}">{{ page }}</a>
        {% endif %}

    {% endfor %}
    {% if has_next %}
       <a class="extend next" rel="next" href="{% url 'index_page' next_page_number %}">Next »</a>
    {% endif %}
    </nav>
    <script>
document.addEventListener('DOMContentLoaded', function() {
    const followButtons = document.querySelectorAll('.follow-button');

    followButtons.forEach(button => {
        button.addEventListener('click', function(event) {
            event.preventDefault();

            if (button.classList.contains('active')) {
                // 如果当前是已关注状态，变为未关注
                button.classList.remove('active');
                button.querySelector('.icon').textContent = '+';
                button.querySelector('.text').textContent = '关注';
                sendFollowRequest(button, false);
            } else {
                // 如果当前是未关注状态，变为已关注
                button.classList.add('active');
                button.querySelector('.icon').textContent = '✓';
                button.querySelector('.text').textContent = '正在关注';
                sendFollowRequest(button, true);
            }
        });
    });

    function sendFollowRequest(button, isFollow) {
        const authorId = button.getAttribute('data-author-id');
        const url = '/follow/' + authorId + '/';
        const method = isFollow ? 'POST' : 'DELETE';

        fetch(url, {
            method: method,
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCookie('csrftoken')
            },
            body: JSON.stringify({ is_follow: isFollow })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                console.log(`User ${isFollow ? 'followed' : 'unfollowed'} the author with ID ${authorId}.`);
            } else {
                console.error('Failed to update follow status.');
            }
        })
        .catch(error => {
            console.error('Error:', error);
        });
    }

    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
});
</script>

</div>
{% endblock %}

















































<div id="main">
    <div class="container">
        <section class="latest-articles">
            <h2 style="text-align:center; font-size:20px; margin-bottom:40px;">最新文章</h2>
            {% if articles %}
                {% for article in articles %}
                <article class="article-box">
                    <h3 style="text-align:center; font-weight: bold;">{{ article.title }}</h3>
                    <p class="meta">
                        作者：{{ article.author }}
                        <a href="#" class="follow-button" data-author-id="{{ article.author.id }}">
                            <span class="icon">+</span>
                            <span class="text">关注</span>
                        </a>
                    </p>
                    <p>
                        创建时间：{{ article.create_time }} · 修改时间：{{ article.update_time }} · {{article.comment_count}} 评论 · {{ article.views }} 阅读
                    </p>
                    <p>{{ article.content | truncatewords:1}}</p>
                    <div class="entry-meta">
                        <span class="article.category"><a href="#">{{ article.category.name }}</a></span>
                    </div>
                    <a href="{% url 'article_detail' article_id=article.id %}" style="display: block; text-align: center;">继续阅读</a>
                </article>
                {% endfor %}
            {% else %}
                <p>暂无文章。</p>
            {% endif %}
        </section>
    </div>

    <nav id="page-nav">
    {% if has_previous %}
       <a class="extend prev" rel="prev" href="{% url 'index_page' previous_page_number %}">« Prev</a>
    {% endif %}
    {% for page in page_list %}
        {% if current_page == page %}
          <a class="page-number current" href="{% url 'index_page' page %}">{{ page }}</a>
        {% else %}
        <a class="page-number" href="{% url 'index_page' page %}">{{ page }}</a>
        {% endif %}

    {% endfor %}
    {% if has_next %}
       <a class="extend next" rel="next" href="{% url 'index_page' next_page_number %}">Next »</a>
    {% endif %}
    </nav>
    <script>
document.addEventListener('DOMContentLoaded', function() {
    const followButtons = document.querySelectorAll('.follow-button');

    followButtons.forEach(button => {
        button.addEventListener('click', function(event) {
            event.preventDefault();

            if (button.classList.contains('active')) {
                // 如果当前是已关注状态，变为未关注
                button.classList.remove('active');
                button.querySelector('.icon').textContent = '+';
                button.querySelector('.text').textContent = '关注';
                sendFollowRequest(button, false);
            } else {
                // 如果当前是未关注状态，变为已关注
                button.classList.add('active');
                button.querySelector('.icon').textContent = '✓';
                button.querySelector('.text').textContent = '正在关注';
                sendFollowRequest(button, true);
            }
        });
    });

    function sendFollowRequest(button, isFollow) {
        const authorId = button.getAttribute('data-author-id');
        const url = '/follow/' + authorId + '/';
        const method = isFollow ? 'POST' : 'DELETE';

        fetch(url, {
            method: method,
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCookie('csrftoken')
            },
            body: JSON.stringify({ is_follow: isFollow })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                console.log(`User ${isFollow ? 'followed' : 'unfollowed'} the author with ID ${authorId}.`);
            } else {
                console.error('Failed to update follow status.');
            }
        })
        .catch(error => {
            console.error('Error:', error);
        });
    }

    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
});
</script>

</div>